var net = require('net');
var tcp_server = net.createServer();  // 创建 tcp server

var Sockets = {};
var SocketID = 1;

// 监听 端口
tcp_server.listen(5678,function (){
    console.log('tcp_server listening 5678');
});

// 处理客户端连接
tcp_server.on('connection',function (socket){
    console.log(socket.address());
    Sockets[SocketID] =socket;
    SocketID++;
    DealConnect(socket)
})

tcp_server.on('error', function (){
    console.log('tcp_server error!');
})

tcp_server.on('close', function () {
    console.log('tcp_server close!');
})


// 处理每个客户端消息
function DealConnect(socket){

    socket.on('data',function(data){
        data = data.toString();
        // 向所有客户端广播消息
       for(var i in Sockets){
           Sockets[i].write(data);
       }
        // socket.write(data);
        console.log('received data %s',data);
    })

    // 客户端正常断开时执行
    socket.on('close', function () {
        console.log('client disconneted!');
    })
// 客户端正异断开时执行
    socket.on("error", function (err) {
        console.log('client error disconneted!');
    });
}


// 指定连接的tcp server ip，端口
var options = {
    host : '127.0.0.1',  
    port : 5678
}

var tcp_client = net.Socket();

// 连接 tcp server
tcp_client.connect(options, function(){
    console.log('connected to Server');
    tcp_client.write('I am tcp_client of node!');
})

// 接收数据
tcp_client.on('data',function(data){
    console.log('received data: %s from server', data.toString());
})

tcp_client.on('end',function(){
    console.log('data end!');
})

tcp_client.on('error', function () {
    console.log('tcp_client error!');
})
